import { useEffect, useRef, useState } from "react";
import { Button, InputNumber, List, message, Modal, Space, Tag } from "antd";
import { Style } from "ol/style";

import { CloseCircleOutlined, CloseOutlined, PlayCircleOutlined } from "@ant-design/icons";
import { drawCircle, geoJsonToFeature, geomToGeoJson, geomToWkt, navByWkt, wktToGeom } from "../../../../../../../utils/helper/mapHelper";

import { fromCircle } from "ol/geom/Polygon";
import { Feature } from "ol";
import useMap from "../../hooks/useMap";
import ZhfxApi from "../../../../../../../utils/apis/ZhfxApi";
import LittleTitle from "../../../../../../common/LittleTitle";
import ScrollTable from "../../../../../../common/ScrollTable";
import CztApi from "../../../../../../../utils/apis/CztApi";
import YxdjypResult from "./YxdjypResult";

export default function Yxdjyp(props) {
    const ref = useRef();
    const map = useMap();
    const [visible, setVisible] = useState();
    const [selectedItems, setSelectedItems] = useState([]);
    const [datas, setDatas] = useState();
    const [params, setParams] = useState({
        pageNum: 1,
        pageSize: 10
    });
    const [total, setTotal] = useState();
    const [loading, setLoading] = useState();

    useEffect(() => {
        if (visible) {
            ZhfxApi.list(params).then(resp => {
                setDatas(resp.rows);
                setTotal(resp.total);
            })
        }
    }, [visible, params])
    return <Space direction='vertical' style={{
        width: '100%'
    }}>
        <Space className="w100" direction="vertical">
            <LittleTitle fontsize={16} icon={false}>选择隐患点</LittleTitle>
            <List header={<div>请至少添加两个隐患点</div>} bordered size="small" dataSource={selectedItems} renderItem={(item) => {
                return <List.Item style={{
                    position: 'relative'
                }}>
                    <div className="layout-h center w100" style={{
                        paddingRight: 12
                    }}>
                        <div className="fill w0">{item.yhmc}</div>
                        <InputNumber value={item.radius} onChange={value => {
                            item.radius = value;
                            setSelectedItems([...selectedItems]);
                        }} style={{
                            width: 100,
                        }} addonAfter={'km'} placeholder="半径" />
                        <Button size="small" type="text" icon={<CloseCircleOutlined />} title="移除" style={{
                            position: "absolute",
                            right: 0,
                            top: "calc(50% - 12px)"
                        }} onClick={e => {
                            setSelectedItems((items) => {
                                const i = items.findIndex(d => d === item);
                                items.splice(i, 1);
                                return [...items]
                            })
                        }}></Button>
                    </div>
                </List.Item>
            }} />
            {/* {selectedItems.map((item, i) => {
                return <Tag key={i} closable onClose={e => {
                    setSelectedItems((items) => {
                        items.splice(i, 1);
                        return [...items]
                    })
                }}>{item.yhmc}</Tag>
            })} */}
            <Button style={{
                width: '100%',
                textAlign: "center"
            }} size="small" type="link" onClick={e => {
                setVisible(true)
            }}>添加隐患点</Button>
            <Modal wrapClassName="modal-main" title="选择隐患点" open={visible} onCancel={e => {
                setVisible(false);
            }} width={700} bodyStyle={{
                height: 350,
                overflow: 'hidden'
            }} footer={[]}>
                <div className='layout-v wh100'>
                    <div className='fill h0' ref={ref}>
                        <ScrollTable otherHeight={72} parentNode={ref.current} columns={[{
                            dataIndex: 'yhmc',
                            title: '隐患名称'
                        }, {
                            dataIndex: 'yhlx',
                            title: '隐患类型',
                            width: 120,
                        }, {
                            width: 80,
                            render: (text, record) => {
                                return <Button type="link" size='small' onClick={e => {
                                    record.geom && navByWkt(record.geom, map, false, true);
                                    setSelectedItems(items => {
                                        return [...items, record];
                                    })
                                    setVisible(false);
                                }}>选择</Button>
                            }
                        }]} dataSource={datas}
                            pagination={{
                                current: params.pageNum,
                                pageSize: params.pageSize,
                                total,
                                onChange: (page) => {
                                    setParams(params => {
                                        return {
                                            ...params,
                                            pageNum: page
                                        }
                                    })
                                },
                                style: {
                                    margin: "8px 0"
                                }
                            }}
                            size="small"
                        />
                    </div>
                </div>
            </Modal>

            {selectedItems.length >= 2 && < div style={{
                marginTop: 16,
                textAlign: "right"
            }}>
                <Button type="primary" loading={loading} onClick={e => {
                    if (map) {
                        let highlightLayer = map?.getLayers()?.getArray()?.find(layer => {
                            return layer.get('id') === 'highlight-layer'
                        });
                        highlightLayer?.getSource?.().clear();
                        const promises = [], polygons = [];
                        let intersectPolygon;
                        for (let i = 0; i < selectedItems.length; i++) {
                            let selectedItem = selectedItems[i];

                            //部分数据只有经度和纬度，geom字段为空
                            if (selectedItem.geom == null) {
                                if (selectedItem.jd && selectedItem.wd) {
                                    selectedItem.geom = `POINT(${selectedItem.jd} ${selectedItem.wd})`
                                }
                            }
                            //console.log('selectedItem',selectedItem)
                            const center = wktToGeom(selectedItem.geom).getCoordinates();
                            if (!selectedItem.radius) {
                                message.error(`${selectedItem.yhmc} 隐患点未输入半径`);
                                return;
                            }
                            const circle = drawCircle(map, center, selectedItem.radius, {
                                noClear: true
                            });
                            const polygon = fromCircle(circle);
                            polygons.push(polygon)
                            const wkt = geomToWkt(polygon);
                            navByWkt(wkt, map, true);
                            promises.push({
                                request: CztApi.listByPolygon2(wkt),
                                item: selectedItem,
                                geometry: polygon
                            })
                        }
                        polygons.forEach((polygon, i) => {

                            if (!intersectPolygon) {
                                intersectPolygon = geomToGeoJson(polygon);
                            } else {
                                const poly = geomToGeoJson(polygon)
                                intersectPolygon = window.turf.intersect(intersectPolygon, poly);
                            }
                        });
                        if (intersectPolygon) {
                            const feature = geoJsonToFeature(intersectPolygon);
                            highlightLayer?.getSource?.().addFeature(feature)
                            promises.push({
                                request: CztApi.listByPolygon2(geomToWkt(feature.getGeometry())),
                                item: {
                                    yhmc: '隐患叠加处'
                                },
                                geometry: feature.getGeometry()
                            })
                        }
                        setLoading(true)
                        Promise.all(promises.map(p => {
                            return p.request
                        })).then(resps => {
                            map.dispatchEvent({
                                type: 'detail.show',
                                title: '分析结果',
                                component: <YxdjypResult result={{
                                    data: resps.map((resp, i) => {
                                        return {
                                            resp,
                                            item: promises[i].item,
                                            geometry: promises[i].geometry
                                        }
                                    })
                                }} />
                            })
                        }).finally(e => { setLoading(false) })
                    }

                }} icon={<PlayCircleOutlined />}>开始分析</Button>
            </div>
            }
        </Space>
    </Space>
}